﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Minio;
using Minio.Exceptions;
using Org.BouncyCastle.Asn1.Cms;
using StoreIModels;
using StoreISet.Applicationes.Command;
using System.Reactive.Linq;

namespace StoreISet.Controllers
{
    /// <summary>
    /// 上传图片
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PicturesController : ControllerBase
    {
        private readonly MinioClient _minioClient;
        private readonly string _bucketName;

        public IMediator _mediator;

        public PicturesController(IMediator mediator, IConfiguration configuration)
        {
            _mediator = mediator;
            var endpoint = configuration.GetValue<string>("MinIO:Endpoint");
            var accessKey = configuration.GetValue<string>("MinIO:AccessKey");
            var secretKey = configuration.GetValue<string>("MinIO:SecretKey");
            _bucketName = configuration.GetValue<string>("MinIO:BucketName");
            _minioClient = new MinioClient(endpoint, accessKey, secretKey);
        }

        /// <summary>
        /// 文件添加
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
       
        public async Task<IActionResult> Upload(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return BadRequest("Invalid file");

            var objectName = file.FileName; // 使用原始文件名作为对象名称

            await _minioClient.PutObjectAsync(_bucketName, objectName, file.OpenReadStream(), file.Length, file.ContentType);

            var url = $"http://10.31.56.32:9001/{_bucketName}/{objectName}";

            return Ok(objectName);
        }
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="objectName"></param>
        /// <returns></returns>
        [HttpGet]
     
        public async Task<IActionResult> Download(string objectName)
        {
            try
            {
                // 检查是否存在与指定前缀匹配的对象
                var objectExists = await _minioClient.ListObjectsAsync(_bucketName, prefix: objectName).ToList();
                if (objectExists.Count == 0)
                {
                    return Ok("未找到该图像");
                }
                // 添加适当的图片文件扩展名
                if (!objectName.Contains("."))
                {
                    var metaData = await _minioClient.ListObjectsAsync(_bucketName, prefix: objectName).FirstAsync();
                    
                    objectName = metaData.Key;
                  
                }
              
                // 创建一个内存流
                using (var memoryStream = new MemoryStream())
                {
                    // 将对象内容复制到内存流中
                    await _minioClient.GetObjectAsync(_bucketName, objectName, (stream) => {
                        stream.CopyTo(memoryStream);
                    });

                    memoryStream.Position = 0;

                    // 复制内存流并创建新的内存流
                    var copiedMemoryStream = new MemoryStream(memoryStream.ToArray());

                    // 返回文件流
                    return File(copiedMemoryStream, "application/octet-stream", objectName);
                }

            }
            catch (MinioException ex)
            {
                // 处理 Minio 异常
                return BadRequest(ex.Message);
            }
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddPicture(PictureCreateCommand command)
        {
            try
            {
                return await _mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
            
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> DelPicture(PictureDeleteCommand command)
        {
            try
            {
                return await _mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
            
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdPicture(PictureUpdateCommand command)
        {
            try
            {
                return await _mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
            
        }
    }
}
